/*
 * Copyright (c) 2010 CCX(China) Co.,Ltd. All Rights Reserved.
 *
 * This software is the confidential and proprietary information of
 * CCX(China) Co.,Ltd. ("Confidential Information").
 * It may not be copied or reproduced in any manner without the express 
 * written permission of CCX(China) Co.,Ltd.
 *
 * @author gyz
 * Date: 2010-7-5 下午12:45:53
 */
package com.ccxe.manage.web;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.List;
import java.util.Random;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.ccxe.manage.bo.OperatorPassword;
import com.ccxe.manage.db.CcxDBOracle;
import com.ccxe.manage.page.PagerList;
import com.ccxe.manage.security.JiaMiUtil;

/**
 * @author gyz
 * 
 */
public class PasswordServlet extends HttpServlet {
	
	private static final long serialVersionUID = 1L;

	/**
	 * 接收请求并分发
	 */
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		
		String methodName=req.getParameter("method");
		String currentPageString=req.getParameter("currentPage");
		int currentPage=1;
		if(currentPageString!=null&&!"".equals(currentPageString)&&!"null".equals(currentPageString))currentPage=(new Integer(currentPageString)).intValue();
		
		if("add".equals(methodName)){
			this.getServletConfig().getServletContext().getRequestDispatcher("/jsp/password/passwordManagerSave.jsp").forward(req, resp);
		}else{
			String userId=(String)req.getSession().getAttribute("userName");
			req.setAttribute("userId", userId);//登录用户id
			List<OperatorPassword> managerList=new ArrayList<OperatorPassword>();
			Connection conn=null;
			try {
				CcxDBOracle ccxDBOracle=new CcxDBOracle();
				conn=ccxDBOracle.getConnection();
				ResultSet rs =ccxDBOracle.executeQuery("select * from C_OPERATOR_PASSWORD a left join C_OPERATOR b on a.OPERATOR_ID=b.OPERATOR_ID");
				
				while(rs.next()){ 
				    OperatorPassword operatorPassword=new OperatorPassword();
				    operatorPassword.setPwdChangeDate(rs.getDate("PWD_CHANGE_DATE"));
				    operatorPassword.setOperatorId(rs.getString("OPERATOR_ID"));
				    operatorPassword.setOperatorName(rs.getString("operator_name"));
				    managerList.add(operatorPassword);
				} 
				
				int pageSize=10;
				PagerList pagerList=new PagerList(managerList,currentPage,pageSize);
				
				req.setAttribute("pagerList", pagerList);
				req.setAttribute("totalSize", ""+managerList.size());
			} catch (Exception e) {
				e.printStackTrace();
			}finally{
				try {
					conn.close();
				} catch (SQLException e) {
					e.printStackTrace();
				}
			}
			this.getServletConfig().getServletContext().getRequestDispatcher("/jsp/password/passwordManager.jsp").forward(req, resp);
		}
		
	}
	
    /**
     *接收请求并分发 
     */
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		 
		String methodName=req.getParameter("method");//新密码
		if("save".equals(methodName)){
			doSave(req,resp);
		}else if("modify".equals(methodName)){
			String pp=(String)req.getParameter("currentPage");
			req.setAttribute("currentPage",req.getParameter("currentPage"));
			doModify(req,resp);
		}  else if("update".equals(methodName)){
			String pp=(String)req.getParameter("currentPage");
			req.setAttribute("currentPage",req.getParameter("currentPage"));
			doUpdate(req,resp);
		}else if("delete".equals(methodName)){
			doDelete(req,resp);
		}else if("go2Page".equals(methodName)){
			doGet(req,resp);
		}else if("checkoperatorId".equals(methodName)){
			doCheck(req,resp);
		}else{
			//req.getSession().setAttribute("userName", req.getParameter("userName"));
			String newPassword=req.getParameter("newPassword");//新密码
			String jiaMiString=stringJiaMi(newPassword);//加密后的密码
			
			String operatorId=req.getParameter("operatorId");//当前id
			CcxDBOracle ccxDBOracle=null;
			try {
				ccxDBOracle=new CcxDBOracle();
				ccxDBOracle.setAutoCommit(false);
				
				Object[]sqlParameters1=new Object[2];
				sqlParameters1[0]=jiaMiString;
				sqlParameters1[1]=operatorId;
				
				String sqlString="update C_OPERATOR_PASSWORD a SET a.PASSWORD=? where a.OPERATOR_ID=?";
				ccxDBOracle.executeUpdate(sqlString, sqlParameters1);
				
				Object[] sqlParameters2=new Object[2];
				
				GregorianCalendar gregorianCalendar = new GregorianCalendar(); 
				gregorianCalendar.setTime(new Date());
				
				java.sql.Date sqldate = new java.sql.Date(((Date)gregorianCalendar.getTime()).getTime());  
				
				sqlParameters2[0]=sqldate; 
				sqlParameters2[1]=operatorId;
				
				String sqlString2="update C_OPERATOR b SET b.PWD_CHANGE_DATE=? where b.OPERATOR_ID=?";
				ccxDBOracle.executeUpdate(sqlString2, sqlParameters2);
				ccxDBOracle.commit();
			} catch (Exception e) {
				e.printStackTrace();
				try {
					ccxDBOracle.rollback();
				} catch (Exception e1) {
					e1.printStackTrace();
				}
			}
			doGet(req,resp);
		}
		
		
	}
	
	/**
	 * 对字符串加密，返回加密后的字符串
	 * @param s
	 * @return
	 */
	public String stringJiaMi(String s){
		
		JiaMiUtil jiaMiUtil=new JiaMiUtil(s);
		String postString = jiaMiUtil.compute();
		
		return postString;
	}
    
	/**
	 * 取得将要修改记录的基本信息，转到修改页面
	 * @param req
	 * @param resp
	 * @throws ServletException
	 * @throws IOException
	 */
	 protected void doModify(HttpServletRequest req, HttpServletResponse resp)
		throws ServletException, IOException {
	       String operatorId=req.getParameter("operatorId");//当前id
	       CcxDBOracle ccxDBOracle=null;
			try {
				ccxDBOracle=new CcxDBOracle();
				ccxDBOracle.setAutoCommit(false);
				
				GregorianCalendar gregorianCalendar = new GregorianCalendar(); 
				gregorianCalendar.setTime(new Date());
				java.sql.Date sqldate = new java.sql.Date(((Date)gregorianCalendar.getTime()).getTime());  
				
				Object[]sqlParameters1=new Object[1];
				sqlParameters1[0]=operatorId;
				
				String sqlString="select * from C_OPERATOR where operator_id=?";
				ResultSet rs =ccxDBOracle.executeQuery(sqlString, sqlParameters1);
				
				List managerList=new ArrayList();
				while(rs.next()){ 
				    OperatorPassword operatorPassword=new OperatorPassword();
				    operatorPassword.setPwdChangeDate(rs.getDate("PWD_CHANGE_DATE"));//密码修改时间
				    operatorPassword.setOperatorId(rs.getString("OPERATOR_ID"));//主键id
				    operatorPassword.setOperatorName(rs.getString("operator_name"));//姓名
				    operatorPassword.setAcountDeleted(rs.getString("ACCOUNT_DELETED"));//是否禁用
				    operatorPassword.setPwdExpireDate(rs.getDate("PWD_EXPIRY_DATE"));//密码过期时间
				    operatorPassword.setPwdChangeDate(rs.getDate("PWD_CHANGE_DATE"));//上次修改密码时间
				    managerList.add(operatorPassword);
				} 
				OperatorPassword operatorPasswordResult=null;
				if(managerList!=null){
					operatorPasswordResult=new OperatorPassword();
					operatorPasswordResult=(OperatorPassword)managerList.get(0);
					
				}
				ccxDBOracle.commit();
				req.setAttribute("operatorPassword", operatorPasswordResult);
			} catch (Exception e) {
				e.printStackTrace();
				try {
					ccxDBOracle.rollback();
				} catch (Exception e1) {
					e1.printStackTrace();
				}
			}
			this.getServletConfig().getServletContext().getRequestDispatcher("/jsp/password/passwordManagerModify.jsp").forward(req, resp);
	    }
	 
	 /**
	  * 删除管理员
	  */
	 protected void doDelete(HttpServletRequest req, HttpServletResponse resp)
		throws ServletException, IOException {
		  String operatorId=req.getParameter("operatorId");//当前id
	       CcxDBOracle ccxDBOracle=null;
			try {
				ccxDBOracle=new CcxDBOracle();
				ccxDBOracle.setAutoCommit(false);
				
				Object[]sqlParameters1=new Object[1];
				sqlParameters1[0]=operatorId;
				
				String sqlString="delete from C_OPERATOR where operator_id=?";
				ccxDBOracle.executeUpdate(sqlString, sqlParameters1);
				
				String sqlString2="delete from C_OPERATOR_PASSWORD where operator_id=?";
				ccxDBOracle.executeUpdate(sqlString2, sqlParameters1);
				
				ccxDBOracle.commit();
			} catch (Exception e) {
				e.printStackTrace();
				try {
					ccxDBOracle.rollback();
				} catch (Exception e1) {
					e1.printStackTrace();
				}
			}
			doGet(req,resp);
	 }
	 
	 /**
	  *保存管理员信息 
	  * @param req
	  * @param resp
	  * @throws ServletException
	  * @throws IOException
	  */
    protected void doSave(HttpServletRequest req, HttpServletResponse resp)
	throws ServletException, IOException {
      
    	String operatorId=req.getParameter("operatorId");
        String operatorName=req.getParameter("operatorName");//姓名
        String acountDeleted=req.getParameter("acountDeleted");//是否禁用
        String pwdExpireDateTemp=req.getParameter("pwdExpireDate");//密码过期时间
    	
    	Random random=new Random();
    	String reSubmitFlag=""+random.nextInt();
    	
    	HttpSession session=req.getSession();
    	
    	if(session.getAttribute("reSubmitFlag")==null){
    		session.setAttribute("reSubmitFlag",reSubmitFlag);
    	}
      
        	SimpleDateFormat simpleDateFormat=new SimpleDateFormat("yyyy-MM-dd");
            Date pwdExpireDate=null;
            try {
     		  pwdExpireDate=simpleDateFormat.parse(pwdExpireDateTemp);//密码过期时间
     	   } catch (ParseException e2) {
     		  e2.printStackTrace();
     	   }

     	   GregorianCalendar gregorianCalendar = new GregorianCalendar(); 
     	   gregorianCalendar.setTime(new Date());
     	   java.sql.Date sqldate = new java.sql.Date(((Date)gregorianCalendar.getTime()).getTime());  
     	   gregorianCalendar.setTime(pwdExpireDate);
     	   java.sql.Date pwdExpireDateResult = new java.sql.Date(((Date)gregorianCalendar.getTime()).getTime());//密码过期时间
     	   
            String password=req.getParameter("password");
            String jiaMiString=stringJiaMi(password);//加密后的密码
            CcxDBOracle ccxDBOracle=null;
     		try {
     			ccxDBOracle=new CcxDBOracle();
     			ccxDBOracle.setAutoCommit(false);
     			if(session.getAttribute("reSubmitFlag").equals(reSubmitFlag)){
     				Object[]sqlParameters1=new Object[5];
     				
     				sqlParameters1[0]=operatorId;//32位不重复随机数
     				sqlParameters1[1]=operatorName;//姓名
     				sqlParameters1[2]=acountDeleted;//是否禁用
     				sqlParameters1[3]=pwdExpireDateResult;//密码过期时间
     				sqlParameters1[4]=sqldate;//上次更改密码时间
     				
     				String sqlString="insert into C_OPERATOR values(?,?,'',?,'','',?,?)";
     				ccxDBOracle.executeUpdate(sqlString, sqlParameters1);
     				
     				Object[] sqlParameters2=new Object[2];
     				sqlParameters2[0]=operatorId; //32位不重复随机数
     				sqlParameters2[1]=jiaMiString;
     				
     				String sqlString2="insert into C_OPERATOR_PASSWORD values(?,'',?)";
     				ccxDBOracle.executeUpdate(sqlString2, sqlParameters2);
     			 }
     				
                 ResultSet rs =ccxDBOracle.executeQuery("select * from C_OPERATOR_PASSWORD a left join C_OPERATOR b on a.OPERATOR_ID=b.OPERATOR_ID");
     				
     				List<OperatorPassword> managerList=new ArrayList<OperatorPassword>();
     				while(rs.next()){ 
     				    OperatorPassword operatorPassword=new OperatorPassword();
     				    operatorPassword.setPwdChangeDate(rs.getDate("PWD_CHANGE_DATE"));
     				    operatorPassword.setOperatorId(rs.getString("OPERATOR_ID"));
     				    operatorPassword.setOperatorName(rs.getString("operator_name"));
     				    managerList.add(operatorPassword);
     				} 
     				int currentPage=1;
     				int pageSize=10;
     				PagerList pagerList=new PagerList(managerList,currentPage,pageSize);
     				
     				req.setAttribute("pagerList", pagerList);
     				req.setAttribute("totalSize", ""+managerList.size());
     				ccxDBOracle.commit();
     				session.removeAttribute("reSubmitFlag");//删除中保存标示，以供保存新数据
     				this.getServletConfig().getServletContext().getRequestDispatcher("/jsp/password/passwordManager.jsp").forward(req, resp);
     		} catch (Exception e) {
     			e.printStackTrace();
     			try {
     				ccxDBOracle.rollback();
     			} catch (Exception e1) {
     				e1.printStackTrace();
     			}
     		}
     	   req.getSession().removeAttribute("resubmitFlag");
    	
    	
       
      
    }
	
    /**
     * 更新管理员数据
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    protected void doUpdate(HttpServletRequest req, HttpServletResponse resp)
	throws ServletException, IOException {
      
    	String operatorId=req.getParameter("operatorId");
       String operatorName=req.getParameter("operatorName");//姓名
       String acountDeleted=req.getParameter("acountDeleted");//是否禁用
       String pwdExpireDateTemp=req.getParameter("pwdExpireDate");//密码过期时间
       SimpleDateFormat simpleDateFormat=new SimpleDateFormat("yyyy-MM-dd");
       Date pwdExpireDate=null;
       try {
		  pwdExpireDate=simpleDateFormat.parse(pwdExpireDateTemp);//密码过期时间
	   } catch (ParseException e2) {
		  e2.printStackTrace();
	   }

	   GregorianCalendar gregorianCalendar = new GregorianCalendar(); 
	   gregorianCalendar.setTime(new Date());
	   java.sql.Date sqldate = new java.sql.Date(((Date)gregorianCalendar.getTime()).getTime());  
	   gregorianCalendar.setTime(pwdExpireDate);
	   java.sql.Date pwdExpireDateResult = new java.sql.Date(((Date)gregorianCalendar.getTime()).getTime());//密码过期时间
	   
       String password=req.getParameter("password");
       String jiaMiString=stringJiaMi(password);//加密后的密码
       CcxDBOracle ccxDBOracle=null;
		try {
			ccxDBOracle=new CcxDBOracle();
			ccxDBOracle.setAutoCommit(false);
				
				Object[] sqlParameters1=new Object[2];
				sqlParameters1[0]=jiaMiString; 
				sqlParameters1[1]=operatorId; 
				
				String sqlString1="update C_OPERATOR_PASSWORD a SET a.PASSWORD=? where a.OPERATOR_ID=?";
				ccxDBOracle.executeUpdate(sqlString1, sqlParameters1);
				
				Object[] sqlParameters2=new Object[5];
				sqlParameters2[0]=sqldate; 
				sqlParameters2[1]=operatorName; //姓名
				sqlParameters2[2]=acountDeleted;//是否禁用
				sqlParameters2[3]=pwdExpireDateResult;//密码过期时间
				sqlParameters2[4]=operatorId;
				
				String sqlString2="update C_OPERATOR b SET b.PWD_CHANGE_DATE=?,b.OPERATOR_NAME=?,b.ACCOUNT_DELETED=?,b.PWD_EXPIRY_DATE=? where b.OPERATOR_ID=?";
				ccxDBOracle.executeUpdate(sqlString2, sqlParameters2);
				
				ResultSet rs =ccxDBOracle.executeQuery("select * from C_OPERATOR_PASSWORD a left join C_OPERATOR b on a.OPERATOR_ID=b.OPERATOR_ID");
				
				List<OperatorPassword> managerList=new ArrayList<OperatorPassword>();
				while(rs.next()){ 
				    OperatorPassword operatorPassword=new OperatorPassword();
				    operatorPassword.setPwdChangeDate(rs.getDate("PWD_CHANGE_DATE"));
				    operatorPassword.setOperatorId(rs.getString("OPERATOR_ID"));
				    operatorPassword.setOperatorName(rs.getString("operator_name"));
				    managerList.add(operatorPassword);
				} 
				String currentPageString=req.getParameter("currentPage");
				int currentPage=1;
				if(currentPageString!=null)currentPage=(new Integer(currentPageString)).intValue();
				int pageSize=10;
				PagerList pagerList=new PagerList(managerList,currentPage,pageSize);
				
				req.setAttribute("pagerList", pagerList);
				req.setAttribute("totalSize", ""+managerList.size());
				ccxDBOracle.commit();
				this.getServletConfig().getServletContext().getRequestDispatcher("/jsp/password/passwordManager.jsp").forward(req, resp);
			
		} catch (Exception e) {
			e.printStackTrace();
			try {
				ccxDBOracle.rollback();
			} catch (Exception e1) {
				e1.printStackTrace();
			}
		}
    }
    
    /**
     * 转到新增管理员页面
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    protected void doAdd(HttpServletRequest req, HttpServletResponse resp)
	throws ServletException, IOException {
         this.getServletConfig().getServletContext().getRequestDispatcher("/jsp/password/passwordManagerModify.jsp").forward(req, resp);
    }
    
    /**
     * 验证新增的管理员id是否已经存在
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    protected void doCheck(HttpServletRequest req, HttpServletResponse resp)
	throws ServletException, IOException {
    	 String resultString="no";
    	 
    	 String operatorId=req.getParameter("operatorId");//登录id
    	 
    	 CcxDBOracle ccxDBOracle=null;
		try {
			ccxDBOracle = new CcxDBOracle();
            ResultSet rs =ccxDBOracle.executeQuery("select * from C_OPERATOR_PASSWORD a where a.OPERATOR_ID='"+operatorId+"'");
			
			List<OperatorPassword> managerList=new ArrayList<OperatorPassword>();
			while(rs.next()){ 
			    OperatorPassword operatorPassword=new OperatorPassword();
			    operatorPassword.setOperatorId(rs.getString("OPERATOR_ID"));
			    managerList.add(operatorPassword);
			} 
			if(managerList==null||managerList.size()==0){
				resultString="ok";
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		resp.setContentType("text/plain");
         PrintWriter p=(PrintWriter)resp.getWriter();
         p.print(resultString);
    }
    
    /**
     * 自动生成8位随机字符串--先生成32位不可重复随机字符串，再截取前8位作为目标字符串返回
     * @return
     */
//    public String getCode() {
//    	String temp32=new String(Hex.encodeHex(org.apache.commons.id.uuid.UUID.randomUUID().getRawBytes()));
//    	  return temp32.substring(0,8);
//    }
    
}
